<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item>
        <el-input v-model="queryParams.editionNum" placeholder="请输入版本号" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-select v-model="queryParams.isRenew" placeholder="请选择是否强制更新" clearable>
          <el-option v-for="dict in [{ val: 1, lab: '是' }, { val: 0, lab: '否' }]" :key="dict.val" :label="dict.lab"
            :value="dict.val" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="queryParams.isUse" placeholder="请选择是否启用" clearable>
          <el-option v-for="dict in [{ val: 1, lab: '启用' }, { val: 0, lab: '禁用' }]" :key="dict.val" :label="dict.lab"
            :value="dict.val" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:config:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:config:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:config:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:config:export']">导出</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-refresh" size="mini" @click="handleRefreshCache"
          v-hasPermi="['system:config:remove']">刷新缓存</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="appList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="应用名称" align="center" prop="appName" />
      <el-table-column label="版本号" align="center" prop="editionNum" :show-overflow-tooltip="true" />
      <el-table-column label="版本描述" align="center" prop="functionDesc" :show-overflow-tooltip="true" />
      <el-table-column label="是否需要强制更新" align="center" prop="isRenew" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.isRenew * 1 ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否启用" align="center" prop="isUse">
        <template slot-scope="scope">
          <span>{{ scope.row.isUse * 1 ? '启用' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.uploadTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上传人" align="center" prop="uploadUser" :show-overflow-tooltip="true" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button class="btn rr" type="danger" plain size="mini" @click="handleDelete(scope.row)">删除</el-button>
          <el-button class="btn" type="primary" plain size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body class="dai" :show-close="false">
      <i class="el-icon-circle-close close_i" @click="cancel"></i>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="form.appName" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item label="版本号" prop="editionNum">
          <el-input v-model="form.editionNum" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="文件地址" prop="filePath">
          <el-upload class="upimg" action="#" :http-request="requestUpload" :show-file-list="false"
            :before-upload="beforeUpload">
            <el-button size="small">
              选择
              <i class="el-icon-upload el-icon--right"></i>
            </el-button>
          </el-upload>
          <div v-if="filePath" style="margin-right: 30px;margin-left: 30px;"><i class="el-icon-document"></i>{{
            filePath }}</div>
        </el-form-item>
        <el-form-item label="功能描述" prop="functionDesc">
          <el-input v-model="form.functionDesc" placeholder="请输入功能描述" />
        </el-form-item>
        <el-form-item label="是否需要强制更新" prop="isRenew">
          <el-radio-group v-model="form.isRenew">
            <el-radio v-for="dict in [{ val: 1, lab: '是' }, { val: 0, lab: '否' }]" :key="dict.val" :label="dict.val">
              {{ dict.lab }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否启用" prop="isUse">
          <el-radio-group v-model="form.isUse">
            <el-radio v-for="dict in [{ val: 1, lab: '启用' }, { val: 0, lab: '禁用' }]" :key="dict.val"
              :label="dict.val">{{
                dict.lab
              }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { applist, addApp, deleteApp, updateApp, checkApp } from "@/api/system/appmanege";
import { upImg } from "@/api/xzgl/zygl/index";
import { Loading } from 'element-ui';
export default {
  name: "AppVersion",
  data() {
    const validateFilePath = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请上传版本APK包'));
      } else {
        callback(); // 校验通过
      }
    };
    return {
      loadingInstance: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      appList: [],
      // 弹出层标题
      title: "新增",
      // 是否显示弹出层
      open: false,
      // 日期范围
      filePath: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        editionNum: '',
        isUse: '',
        isRenew: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        appName: [
          { required: true, message: "版本名称不能为空", trigger: "blur" }
        ],
        editionNum: [
          { required: true, message: "版本号不能为空", trigger: "blur" }
        ],
        functionDesc: [
          { required: true, message: "功能描述不能为空", trigger: "blur" }
        ],
        isRenew: [
          { required: true, message: "是否需要强制更新", trigger: "change" }
        ],
        isUse: [
          { required: true, message: "是否启用", trigger: "change" }
        ],
        filePath: [
          { required: true, validator: validateFilePath, trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    uploadeImg(file) {
      this.loadingInstance = Loading.service({
        lock: true,
        text: '上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      upImg(file).then(response => {
        this.form.filePath = response.data.filePath
        this.filePath = this.form.filePath ? this.form.filePath.split('/')[5] : ''
        this.loadingInstance.close();
        this.$message({
          message: '上传成功',
          type: 'success'
        });
      }).catch(error => {
        this.loadingInstance.close();
      });
    },
    requestUpload() { },
    beforeUpload(file) {
      const isAPK = file.type === 'application/vnd.android.package-archive'
        || file.name.endsWith('.apk');
      if (!isAPK) {
        this.$message.error('请上传 APK 格式的文件！');
        return false; // 阻止上传
      } else {
        const formData = new FormData();
        formData.append('file', file);
        this.uploadeImg(formData)
      }

      // const formData = new FormData();
      // formData.append('file', file);
      // this.uploadeImg(formData)
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      applist(this.queryParams).then(response => {
        this.appList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        appName: undefined,
        editionNum: undefined,
        filePath: undefined,
        isRenew: undefined,
        isUse: undefined,
        functionDesc: undefined
      };
      this.filePath = ''
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const configId = row.id || this.ids
      checkApp(configId).then(response => {
        this.form = response.data;
        this.form.isRenew = response.data.isRenew * 1
        this.form.isUse = response.data.isUse * 1
        this.filePath = this.form.filePath ? this.form.filePath.split('/')[5] : ''
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateApp(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addApp(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.reset();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let configIds = row.id || this.ids;
      typeof configIds === 'string' && (configIds = [configIds])
      console.log(configIds);
      this.$modal.confirm('是否确认删除参数编号为"' + configIds + '"的数据项？').then(function () {
        return deleteApp(configIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/config/export', {
        ...this.queryParams
      }, `config_${new Date().getTime()}.xlsx`)
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.$modal.msgSuccess("刷新成功");
      });
    }
  }
};
</script>
<style scoped lang="scss">
.btn {
  padding: 5px 10px !important;
  color: #fff;
  background-color: #1890FF !important;
}

.rr {
  background-color: #FF6060 !important;
}

.upimg {
  display: flex;
}

.dai {
  .close_i {
    position: absolute;
    color: #fff;
    top: 20px;
    right: 20px;
    font-size: 20px;
  }

  ::v-deep .el-dialog__title {
    color: #fff;
  }

  ::v-deep .el-form {
    border: 1px solid #CFCCCC;
  }

  ::v-deep .el-form-item__label {
    border-right: 1px solid #CFCCCC;
    border-bottom: 1px solid #CFCCCC;
    margin-bottom: -1px;
    padding-bottom: 1px;
    height: 42px;
  }

  ::v-deep .el-form-item__content {
    border-bottom: 1px solid #CFCCCC;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 42px;
  }

  ::v-deep .el-form-item {
    margin-bottom: 0;
  }

  ::v-deep .el-input {
    width: 98%;
  }

  .al {
    ::v-deep .el-form-item__content {
      justify-content: flex-start;
      padding-left: 9px;
    }

  }

  ::v-deep .el-input__inner {
    border-radius: 0;
    height: 32px;
    line-height: 32px;
  }

  ::v-deep .el-dialog__footer {
    text-align: center;
  }

  ::v-deep .el-button {
    color: #2D75D7;
    border-color: #2D75D7;
  }

  ::v-deep .el-button--primary {
    background-color: #1890FF;
    color: #fff
  }
}

::v-deep .el-input.is-disabled .el-input__inner {
  background-color: #FFF;
  border-color: #efefef;
  color: #000;
  cursor: not-allowed;
}

::v-deep .el-dialog__header {
  background-color: #2D75D7 !important;
}

::v-deep .el-form-item__error {
  z-index: 999
}

::v-deep .el-form-item__label {
  font-weight: normal;
}
</style>